﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;
using System.Reflection;
using System.Globalization;
using System.Threading;
namespace BHXH_NT
{
    public class ModuleBHXH
    {
        public static string connectionString = global::BHXH_NT.Properties.Settings.Default.MISBHXH_NTConnectionString;
        public static string connectionString1 = global::BHXH_NT.Properties.Settings.Default.MISBHXH_NTConnectionString1;
        public static string connectionString2 = global::BHXH_NT.Properties.Settings.Default.MISBHXH_NTConnectionString2;
        public static string strYear;
        public static string strMonths;
        public static string strDate;
        public static string strUser;
        public static string GetYear()
        {
            String queryString = "select right(CAST(DATEPART(yy, getdate()) AS CHAR(4)),2) as year";
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows == true)
                {
                    reader.Read();
                    return reader["year"].ToString();
                }
                else
                {
                    return "";
                }

            }
        }
        public static string GetMonth()
        {
            String queryString = "select right(CAST(DATEPART(yy, getdate()) AS CHAR(4)),2) as year,"
            + " right(CAST(DATEPART(yy, getdate()) AS CHAR(4)),4) as longyear, "
            + " DATEPART(mm, getdate()) as months";
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows == true)
                {
                    reader.Read();
                    return reader["longyear"].ToString() + string.Format("{0:00}", reader["months"]);
                }
                else
                {
                    return "";
                }

            }
        }

        public static string GetDate()
        {
            String queryString = "SELECT rtrim(CAST(DATEPART(mm, getdate()) AS CHAR(2)))  + '/' + "
            + " rtrim(CAST(DATEPART(dd, getdate()) AS CHAR(2)))  + '/' + "
            + " CAST(DATEPART(yyyy, getdate()) AS CHAR(4)) as dates";
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows == true)
                {
                    reader.Read();
                    return reader["dates"].ToString();
                }
                else
                {
                    return "";
                }

            }
        }

        public static String FormatDate(DateTime dt)
        {
            return dt.Month + "/" + dt.Day + "/" + dt.Year;
        }
        public static String FormatDate(String dt)
        {
            return dt.Substring(3, 2) + "/" + dt.Substring(0, 2) + "/" + dt.Substring(6, 4);
        }
        public static string FormatNumner(object dbNumber)
        {
            return Convert.ToDouble(dbNumber).ToString("##.000", System.Globalization.CultureInfo.CreateSpecificCulture("en-EN"));
        }
        public static String CreateRunninNo(Random rnd)
        {
            Char vt1, vt2, vt3;
            string st;
            vt1 = RandomChar(rnd);
            vt2 = RandomChar(rnd);
            vt3 = RandomChar(rnd);
            st = String.Format("{0:000}", DateTime.Now.Millisecond) + String.Format("{0:00}", rnd.Next(0, 99));
            return DateTime.Now.Year.ToString().Substring(2) +
                String.Format("{0:00}", DateTime.Now.Month) +
                String.Format("{0:00}", DateTime.Now.Day) +
                String.Format("{0:00}", DateTime.Now.Hour) +
                String.Format("{0:00}", DateTime.Now.Minute) +
                String.Format("{0:00}", DateTime.Now.Second) +
                st + vt1 + vt2 + vt3;



        }

        public static String CreateRunninNo1(Random rnd)
        {
            Char vt1, vt2, vt3, vt4;
            string st;
            vt1 = RandomChar(rnd);
            vt2 = RandomChar(rnd);
            vt3 = RandomChar(rnd);
            vt4 = RandomChar(rnd);
            st = String.Format("{0:0000}", rnd.Next(0, 9999));
            return st + vt1 + vt2 + vt3 + vt4;
        }
        public static char RandomChar(Random rnd)
        {
            int a;
            Char vt;
            a = rnd.Next(55, 90);
            if (a < 65)
            {

                vt = (char)(a - 7);
            }
            else
            {
                vt = (char)a;
            }
            return vt;
        }
        public static Boolean TestConnect()
        {
            //test connection1
            try
            {
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MISBHXH_NTConnectionString))
                {
                    conn.Open();
                    conn.Close();
                }
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MISBHXH_NTConnectionString1))
                {
                    conn.Open();
                    conn.Close();
                }
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MISBHXH_NTConnectionString2))
                {
                    conn.Open();
                    conn.Close();
                }
                //using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.MISBHXH_NTConnectionString3))
                //{
                //    conn.Open();
                //    conn.Close();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Invalid Connection String");
                return false;
            }
            return true;
        }
        public static void WriteSetting(string key, string value)
        {
            ////load config document for current assembly
            XmlDocument doc = loadConfigDocument();
            // retrieve appSettings node
            XmlNode node = doc.SelectSingleNode("//userSettings//BHXH_NT.Properties.Settings");
            if (node == null)
            {
                throw new InvalidOperationException("appSettings section not found in config file.");
            }
            try
            {
                // select the 'add' element that contains the key
                XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//setting[@name='{0}']", key));
                if (elem != null)
                {
                    // add value for key
                    elem.SetAttribute("value", value);
                }
                else
                {
                    // key was not found so create the 'add' element
                    // and set it's key/value attributes
                    elem = doc.CreateElement("setting");
                    elem.SetAttribute("name", key);
                    elem.SetAttribute("serializeAs", "String");
                    elem.SetAttribute("value", value);
                    node.AppendChild(elem);
                }
                doc.Save(getConfigFilePath());
            }
            catch
            {
                throw;
            }
        }
        public static XmlDocument loadConfigDocument()
        {
            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                doc.Load(getConfigFilePath());
                return doc;
            }
            catch (System.IO.FileNotFoundException e)
            {
                throw new Exception("No configuration file found.", e);
            }
        }
        public static string getConfigFilePath()
        {
            return Assembly.GetExecutingAssembly().Location + ".config";
        }
        public static String KhoangThoiGian(string str1, string str2)
        {
            String thoigian;
            int tuthang, tunam, denthang, dennam;
            tuthang = Convert.ToInt16(str1.Substring(0, 2));
            tunam = Convert.ToInt16(str1.Substring(2, 4));

            denthang = Convert.ToInt16(str2.Substring(0, 2));
            dennam = Convert.ToInt16(str2.Substring(2, 4));

            if (tuthang < denthang)
            {
                thoigian = Convert.ToString(dennam - tunam - 1) + " n¨m " + Convert.ToString(tuthang + 12 - denthang) + "th¸ng";

            }
            else
            {
                thoigian = Convert.ToString(dennam - tunam) + " n¨m " + Convert.ToString(denthang - 1) + "th¸ng";
            }
            return thoigian;
        }
        public static void KhoangThoiGian(string str1, string str2, ref int nam, ref int thang)
        {

            int tuthang, tunam, denthang, dennam;
            tuthang = Convert.ToInt16(str1.Substring(0, 2));
            tunam = Convert.ToInt16(str1.Substring(3, 4));

            denthang = Convert.ToInt16(str2.Substring(0, 2));
            dennam = Convert.ToInt16(str2.Substring(3, 4));

            if (tuthang > denthang)
            {
                nam = nam + dennam - tunam - 1;
                thang = thang + denthang - tuthang + 12 + 1;

            }
            else
            {
                nam = nam + dennam - tunam;
                thang = thang + denthang - tuthang + 1;
            }
            if (thang >= 12)
            {
                nam++;
                thang = thang - 12;
            }

        }
        public static string FormatThangNam(string str)
        {
            return str.Substring(4) + "/" + str.Substring(0, 4);
        }
        public static string Doc_tien_sang_tieng_viet(double N, string DviChan = "", string DviLe = "")
        {

            string Ketqua = null;
            string sotien = null;
            string nhom = null;
            string chu = null;
            string dich = null;
            string s1 = null;
            string S2 = null;
            string s3 = null;
            byte i = 0;
            byte j = 0;
            string[] Hang = new string[4];
            string[] doc = new string[7];
            string[] dem = new string[10];
            double s = 0;

            if (N == 0)
            {
                Ketqua = " kh«ng " + DviChan;
            }
            else
            {
                if (N < 0)
                {
                    Ketqua = "trõ" + Microsoft.VisualBasic.Strings.Space(1);
                }
                else
                {
                    Ketqua = Microsoft.VisualBasic.Strings.Space(0);
                }
                //If InStr(CType(N, String), ",") > 0 Then
                //    DviChan = "phẩy"
                //Else
                //    DviChan = DviLe
                //    DviLe = ""
                //End If
                sotien = Microsoft.VisualBasic.Strings.Format(Math.Abs(N), "##############0.00");
                sotien = Microsoft.VisualBasic.Strings.Right(Microsoft.VisualBasic.Strings.Space(15) + sotien, 18);
                Hang[0] = "";
                Hang[1] = "tr¨m";
                Hang[2] = "m­¬i";
                Hang[3] = "ï";
                //Hang = Array("", "traêm", "möôi", "ù")
                doc[0] = "";
                doc[1] = "ngµn tû";
                doc[2] = "tû";
                doc[3] = "triÖu";
                doc[4] = "ngµn";
                doc[5] = DviChan;
                doc[6] = DviLe;
                dem[0] = "";
                dem[1] = "mét";
                dem[2] = "hai";
                dem[3] = "ba";
                dem[4] = "bèn";
                dem[5] = "n¨m";
                dem[6] = "s¸u";
                dem[7] = "b¶y";
                dem[8] = "t¸m";
                dem[9] = "chÝn";
                for (i = 1; i <= 6; i++)
                {
                    nhom = Microsoft.VisualBasic.Strings.Mid(sotien, i * 3 - 2, 3);
                    if (nhom != Microsoft.VisualBasic.Strings.Space(3))
                    {
                        switch (nhom)
                        {
                            case "000":
                                if (i == 5)
                                {
                                    chu = DviChan + Microsoft.VisualBasic.Strings.Space(1);
                                }
                                else
                                {
                                    chu = Microsoft.VisualBasic.Strings.Space(0);
                                }
                                break;
                            case ".00":
                            case ",00":
                                chu = "";
                                break;
                            default:
                                s1 = Microsoft.VisualBasic.Strings.Left(nhom, 1);
                                S2 = Microsoft.VisualBasic.Strings.Mid(nhom, 2, 1);
                                s3 = Microsoft.VisualBasic.Strings.Right(nhom, 1);
                                chu = Microsoft.VisualBasic.Strings.Space(0);
                                Hang[3] = doc[i];
                                for (j = 1; j <= 3; j++)
                                {
                                    dich = Microsoft.VisualBasic.Strings.Space(0);
                                    s = Microsoft.VisualBasic.Conversion.Val(Microsoft.VisualBasic.Strings.Mid(nhom, j, 1));
                                    if (s > 0)
                                    {
                                        dich = dem[Convert.ToInt16(s)] + Microsoft.VisualBasic.Strings.Space(1) + Hang[j] + Microsoft.VisualBasic.Strings.Space(1);
                                    }
                                    switch (j)
                                    {
                                        case 2:
                                            if (Convert.ToInt16(s) == 1)
                                            {
                                                dich = "m­êi" + Microsoft.VisualBasic.Strings.Space(1);
                                            }
                                            //if (( Convert.ToInt16(s1) >= 1 & Convert.ToInt16(s1) <= 9) || (Convert.ToInt16(s1) == 0 && i == 4) && s == 0 && Convert.ToInt16(s3) != 0) {
                                            //    dich = "linh" + Microsoft.VisualBasic.Strings.Space(1);
                                            //}
                                            break;
                                        case 3:
                                            if (Convert.ToInt16(s) == 0 && nhom != Microsoft.VisualBasic.Strings.Space(2) + "0")
                                            {
                                                dich = Hang[j] + Microsoft.VisualBasic.Strings.Space(1);
                                            }
                                            if (s == 5 & S2 != Microsoft.VisualBasic.Strings.Space(1) & S2 != "0")
                                            {
                                                dich = "l" + Microsoft.VisualBasic.Strings.Mid(dich, 2);
                                            }
                                            break;

                                    }
                                    chu = chu + dich;
                                }

                                break;
                        }
                        //vitri = Microsoft.VisualBasic.Strings.InStr(1, chu, "mươi một", 1);
                        //if (vitri > 0)
                        //    Microsoft.VisualBasic.Strings.Mid(chu, vitri, 9) = "mươi mốt";
                        return Ketqua + chu;
                    }
                }
            }

            return Microsoft.VisualBasic.Strings.UCase(Microsoft.VisualBasic.Strings.Left(Ketqua, 1)) + Microsoft.VisualBasic.Strings.Mid(Ketqua, 2);
        }
        public static System.Array ResizeArray(System.Array oldArray, int newSize)
        {
            int oldSize = oldArray.Length;
            System.Type elementType = oldArray.GetType().GetElementType();
            System.Array newArray = System.Array.CreateInstance(elementType, newSize);
            int preserveLength = System.Math.Min(oldSize, newSize);
            if (preserveLength > 0)
                System.Array.Copy(oldArray, newArray, preserveLength);
            return newArray;
        }

        public static string ChangeToCamel(string str)
        {
            string[] strArr = str.Split(new char[] { ' ' });
            StringBuilder strTemp = new StringBuilder();

            foreach (string subStr in strArr)
            {
                if (subStr != "" )
                {
                    if (subStr.Substring(0, 1) != "ñ" && subStr.Substring(0, 1) != "è" && subStr.Substring(0, 1) != "ý")
                    {
                        strTemp.Append(subStr.Substring(0, 1).ToUpper()).Append(subStr.Substring(1, subStr.Length - 1)).Append(" ");
                    }
                    else
                    {
                        strTemp.Append(subStr.Substring(0, 1)).Append(subStr.Substring(1, subStr.Length - 1)).Append(" ");
                    }
                }
            }
            return strTemp.ToString();
        }

    }
}
